package middleware

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"go_batch_create_orders/admin/model"
	"go_batch_create_orders/utils"
	"net/http"
)

func AdminJwtTokenMiddleware() gin.HandlerFunc {
	var filterRouterSlice = make([]string, 0, 100)
	return func(context *gin.Context) {
		filterRouterSlice = append(filterRouterSlice, "/user/get_token")
		filterRouterSlice = append(filterRouterSlice, "/user/test")
		filterRouterSlice = append(filterRouterSlice, "/user/login")
		requestMethod := context.FullPath()
		data := utils.JsonInit()
		data.SetCode(501)
		if requestMethod == "" {
			data.SetMessage("路由未定义")
			context.JSON(http.StatusNetworkAuthenticationRequired, data)
			context.Abort()
			return
		}
		token := context.GetHeader("token")
		if token == "" {
			filterStatus := true
			for _, v := range filterRouterSlice {
				if requestMethod == v {
					filterStatus = false
					break
				}
			}
			if filterStatus == true {
				data.SetData("")
				data.SetMessage("暂未登录")
				context.JSON(http.StatusNetworkAuthenticationRequired, data)
				context.Abort()
				return
			}

		} else {
			res, err := utils.DecodeSecretKey(token)
			if err != nil || res == nil {
				data.SetMessage("token失效")
				context.JSON(http.StatusNetworkAuthenticationRequired, data)
				context.Abort()
				return
			}
			users := &model.Users{}
			err = json.Unmarshal(res, users)
			if err != nil {
				data.SetMessage("token失效")
				context.JSON(http.StatusNetworkAuthenticationRequired, data)
				context.Abort()
				return
			}
			context.Set("userId", users.Id)
			context.Set("userName", users.UserName)
		}
		context.Next()
	}
}
